<?php

	require_once('/../email/email.php');
	require_once('/../globals.php');
	
	function getAdminNameByID($adminID)
	{
		if(!isset($adminID) || $adminID < 1):
			return "";
		endif;
		require('\..\private\mysqli_connect.php');
		$result = $db->query("select username from administrators where administrators.admin_id = $adminID");
		if($result->num_rows):
			$row = $result->fetch_array();
			return $row['username'];
		else:
			return "";
		endif;
	}	
	
	function getTicketInfo($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		$query = 	'select * from tickets left join users 
					on tickets.user_id = users.user_id
					where tickets.ticket_id = ' . $ticketNumber . '' ;
		// echo "<br/>";
		// var_dump($query);
		$result = $db->query($query);
		if(!$result):
			echo "Unable to display ticket.</br>";
			return null;
		else:
			return $result->fetch_array();
		endif;
	}
	
	/* below: imported display_ticket.php from project 2 */
	
	// require_once('/admin_header.php');
	// require_once('ticket_functions.php');
	// require_once('email.php');
	
	function redirectToEmailUserPage($ticketNumber)
	{
		// $row = getTicketInfo($ticketNumber);
		// $email = $row['sender_email'];
		header("Location: email_user.php?ticketID=" . $ticketNumber);
	}
	
	function redirectToAdminPageAndFindSubmitterTickets($ticketNumber)
	{
		$row = getTicketInfo($ticketNumber);
		$email = $row['sender_email'];
		header("Location: admin_page.php?senderEmail=" . $email);
	}
	
	function redirectToAdminPageAndFindSimilarSubjects($ticketNumber)
	{
		$row = getTicketInfo($ticketNumber);
		$subject = $row['subject'];
		header("Location: admin_page.php?similarSubject=" . $subject);
	}
	
	function reloadPage($ticketNumber)
	{
		header('Location: /proj2/display_ticket.php?ticketID=' . $ticketNumber);
	}
	
	function deleteTicket($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		// var_dump($_SESSION);
		$query = 'delete from tickets where tickets.ticket_id = ' . $ticketNumber;
		// echo "$query<br/>";
		$result = $db->query($query);
		if($result):
			// echo "success</br>";
			return true;
		else:
			// "failure</br>";
			return false;
		endif;
	}
	
	function removeSelfFromTicket($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		// var_dump($_SESSION);
		$query = 'update tickets set tickets.user_id = NULL where tickets.ticket_id = ' . $ticketNumber;
		// echo "$query<br/>";
		$result = $db->query($query);
		if($result):
			// echo "success</br>";
			return true;
		else:
			// "failure</br>";
			return false;
		endif;
	}
	
	function assignSelfToTicket($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		// var_dump($_SESSION);
		$query = 'update tickets set tickets.user_id = ' . $_SESSION['userID'] . ' where tickets.ticket_id = ' . $ticketNumber;
		// echo "$query<br/>";
		$result = $db->query($query);
		if($result):
			// echo "success</br>";
			return true;
		else:
			// "failure</br>";
			return false;
		endif;
	}
	
	function reopenTicket($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		$query = 'update tickets set ticket_is_open = true where tickets.ticket_id = ' . $ticketNumber;
		$result = $db->query($query);
		if($result):
			// echo "success</br>";
			return true;
		else:
			// "failure</br>";
			return false;
		endif;
	}
	
	function closeTicket($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		$query = 'update tickets set ticket_is_open = false where tickets.ticket_id = ' . $ticketNumber;
		$result = $db->query($query);
		if($result):
			// echo "success</br>";
			sendEmailToUserThatTicketWasResolved($ticketNumber);
			return true;
		else:
			// "failure</br>";
			return false;
		endif;
	}
	
	function sendEmailToUserThatTicketWasResolved($ticketNumber)
	{
		$row = getTicketInfo($ticketNumber);
		$sender = "proj3noreply@pitt.edu";
		$receiver = $row['sender_email'];
		$subj = "Ticket Closed: '" . $row['subject'] . "' ID#" . $row['ticket_id'];
		$submitterName = $row['sender_firstname'] . " " . $row['sender_lastname'];		
		$message = "Dear $submitterName,\n\n" . "Ticket # " . $row['ticket_id'] . " has been closed by an administrator.\n" .
				"\tSubject: " . $row['subject']. "\n\tDescription: " . $row['description'];
		sendEmail($sender, $receiver, $subj, $message);
	}
	
	function displayTicket($ticketNumber)
	{
		if(!ticketExists($ticketNumber)):
			echo "<p>Ticket #$ticketNumber does not exist.</p>";
			return;
		endif;
		require('\..\private\mysqli_connect.php');
		$query = 	'select * from tickets left join administrators 
					on tickets.administrator_id = administrators.admin_id
					where tickets.ticket_id = ' . $ticketNumber . '' ;
		// echo "<br/>";
		// var_dump($query);
		$result = $db->query($query);
		if(!$result):
			echo "Unable to display ticket.</br>";
			return false;
		endif;
		$rows = $result->num_rows;
		$row = $result->fetch_array();
		echo '<form action="display_ticket.php" method="post">';
		echo '<input type="hidden" name="ticketID" value="' . $ticketNumber . '">';
		echo '<table style="border-color:black;text-align:center;" width="700" border="1" align="center" cellpadding="2" cellspacing="1" bgcolor="#EEE">';
		renderHeaderRow();
		renderTicketInfo($row);
		renderButtons($ticketNumber, $row);
		echo "</table>";		
		echo '</form>';
		return true;
	}
	
	function ticketExists($ticketNumber)
	{
		require('\..\private\mysqli_connect.php');
		$query = 'select ticket_id from tickets where ticket_id = ' . $ticketNumber;
		$result = $db->query($query);
		// echo "$query<br/>";
		if($result->num_rows > 0):
			// echo "ticket exists";
			return true;
		else:
			// echo "ticket does not exist";
			return false;
		endif;
	}
	
	function renderButtons($ticketNumber, $row)
	{
		echo '<div>';
		$ticketIsOpen = $row['ticket_is_open'];
		if($ticketIsOpen):
			echo '<input type="submit" name="closeTicketSubmit" value="Close Ticket">';
		else:
			echo '<input type="submit" name="reopenTicketSubmit" value="Re-Open Ticket">';
		endif;
		$adminID = $row['administrator_id'];
		if(!isset($adminID) || empty(getAdminNameByID($adminID))):
			echo '<input type="submit" name="assignSelfSubmit" value="Assign Self to Ticket">';
		else:
			// cannot assign self since another admin is already assigned
		endif;
		
		if(currentAdminIsAssignedToThisTicket($row)):
			echo '<input type="submit" name="removeSelfSubmit" value="Remove Self from Ticket">';
		endif;
		
		echo '<input type="submit" name="emailUserSubmit" value="Email User">';
		echo '<input type="submit" name="deleteTicketSubmit" value="Delete Ticket">';
		echo '<input type="submit" name="findSubmitterTicketsSubmit" value="Find Submitter\'s Tickets">';
		echo '<input type="submit" name="findSimilarTicketsSubmit" value="Find Similar Tickets">';
		echo '<input type="submit" name="goBackToAdminPageSubmit" value="Go Back to Admin Page">';
		echo '</div>';
	}
	
	function currentAdminIsAssignedToThisTicket($row)
	{
		$adminID = $row['administrator_id'];
		if(!isset($adminID) || empty(getAdminNameByID($adminID))):
			return false;
		endif;
		if(isset($adminID)):
			$adminUsername = getAdminNameByID($adminID);
			if(!empty($adminUsername) && strcmp($adminUsername, $_SESSION['admin_username']) == 0):
				return true;
			else:
				return false;
			endif;
		endif;
	}
	
	function renderHeaderRow()
	{
		echo 	'<tr>
					<th>
						Ticket #
					</th>
					<th>
						Received
					</th>
					<th>
						Sender Name
					</th>
					<th>
						Sender Email
					</th>
					<th>
						Subject
					</th>
					<th>
						Tech
					</th>
					<th>
						Status
					</th>
				</tr>';
	}
	
	function renderTicketInfo($row)
	{
		echo "<tr>";
		$ticketID = $row['ticket_id'];
		//echo "<br/><br/>row dump: " . var_dump($row);
		echo "<td>" . $ticketID . "</td>";
		echo "<td>" . $row['received'] . "</td>";
		echo "<td>" . $row['sender_firstname'] . ' ' . $row['sender_lastname']. "</td>";
		echo "<td>" . $row['sender_email'] . "</td>";
		echo "<td>" . $row['subject'] . "</td>";
		
		$adminUsername = getAdminNameByID($row['administrator_id']);
		echo "<td>" . $adminUsername . "</td>";
		if($row['ticket_is_open']):
			echo '<td>open</td>';	
		else:
			echo '<td>closed</td>';	
		endif;
		echo "</tr>";
		echo "<tr>";
		echo '<th>Description</th>';
		echo '<td colspan="6">' . $row['description'] . '</td>';
		echo "</tr>";
	}
?>